<?php

/*
 * CopyRight  : (C)2012-2099 HaoTeam Inc.
 * Document   : JsonService.php
 * Created on : 2020-7-25 9:48:34
 * Author     : Tiger <1192851302@qq.com>
 * Description: This is NOT a freeware, use is subject to license terms.
 *              这即使是一个免费软件,使用时也请遵守许可证条款,得到当时人书面许可.
 *              未经书面许可,不得翻版,翻版必究;版权归属 HaoTeam Inc;
 */

namespace haoteam\utils;

use think\Response;

/**
 * 输出服务
 * Class JsonService
 * Tiger <1192851302@qq.com> 2020-7-25 9:48:34
 */
class JsonService {

    private $code = 200;

    public function code(int $code): self {
        $this->code = $code;
        return $this;
    }

    public function make(int $code, string $msg, ?array $data = null): Response {
        $res = compact('code', 'msg');

        if (!is_null($data)) {
            $res['data'] = $data;
        }

        return Response::create($res, 'json', $this->code);
    }

    public function success($msg = 'ok', ?array $data = null): Response {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'ok';
        }

        return $this->make(200, $msg, $data);
    }

    public function successful(...$args): Response {
        return $this->success(...$args);
    }

    public function fail($msg = 'fail', ?array $data = null): Response {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'ok';
        }

        return $this->make(400, $msg, $data);
    }

    public function status($status, $msg, $result = []) {
        $status = strtoupper($status);
        if (is_array($msg)) {
            $result = $msg;
            $msg = 'ok';
        }
        return $this->success($msg, compact('status', 'result'));
    }

}
